package beautiful.butterfly.drds.binlog.zookeeper;

import beautiful.butterfly.drds.binlog.operation.OpeationEvent;
import beautiful.butterfly.drds.binlog.operation.OpeationEventQueue;
import beautiful.butterfly.drds.binlog.operation.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;

@Slf4j
public class TaskListener
{

    ///
    private static TaskListener taskListener;
    private PathChildrenCacheListener pathChildrenCacheListener;

    private TaskListener(PathChildrenCacheListener pathChildrenCacheListener)
    {
        this.pathChildrenCacheListener = pathChildrenCacheListener;
    }

    public static TaskListener getTaskListener()
    {
        if (null == taskListener)
        {
            synchronized (TaskListener.class)
            {
                if (null == taskListener)
                {
                    PathChildrenCacheListener pathChildrenCacheListener = new PathChildrenCacheListener()
                    {
                        @Override
                        public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception
                        {
                            // 正式处理业务
                            switch (pathChildrenCacheEvent.getType())
                            {
                                case CHILD_ADDED:
                                    // 放入队列就闪
                                    OpeationEventQueue.addObject(new OpeationEvent(pathChildrenCacheEvent, OperationType.task_add));
                                    break;
                                case CHILD_UPDATED:
                                    // 放入队列就闪
                                    OpeationEventQueue.addObject(new OpeationEvent(pathChildrenCacheEvent, OperationType.task_update));
                                    break;
                                default:
                                    break;
                            }
                        }
                    };
                    taskListener = new TaskListener(pathChildrenCacheListener);
                }
            }
        }
        return taskListener;
    }

    public PathChildrenCacheListener getPathChildrenCacheListener()
    {
        return pathChildrenCacheListener;
    }
}
